﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Text;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSwaggerGen();
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();

app.MapPost("/api/dosomething", (Par par) =>
{
    Console.WriteLine("dosomething");
    return "1";
}).AddEndpointFilter(async (invocationContext, next) =>
{
    //invocationContext.HttpContext.Request.Body.Position = 0;
    //using var reader = new StreamReader(invocationContext.HttpContext.Request.Body, Encoding.UTF8);
    //var param = reader.ReadToEndAsync().Result; //获取一个json数据

    var request = invocationContext.HttpContext.Request;

    //开启多次读取body流
    request.EnableBuffering();

    //leaveOpen:true标识StreamReader释放时不会自动关闭流        　　
    using var sr = new StreamReader(request.Body, leaveOpen: true, encoding: Encoding.UTF8);

    var paramJson = await sr.ReadToEndAsync();

    var httpcontext=invocationContext.HttpContext.Request;
    Console.WriteLine("123");
    Console.WriteLine(paramJson);
    return await next(invocationContext);
}); ;

app.Run();

internal class Par
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class DoSomethingFitter :IAsyncActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        throw new NotImplementedException();
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        Console.WriteLine("请求之前执行");
        Console.WriteLine(context);
        throw new NotImplementedException();
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        //请求执行之前todo
        await next();
        //请求执行之后todo
    }
}